package com.ikas.ai.server.config.format;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.core.convert.converter.Converter;

import java.util.Date;

/**
 * @Description: 日期转换器
 * @Author: qi.yilai
 * @Date: 2022/3/22 16:55
 * @Version: 1.0.0
 **/
@Slf4j
public class DateConverter implements Converter<String, Date> {
    private static final String TIME_SPLIT = ":";
    private static final String BLANK = " ";
    private static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    private static final String DATE_FORMAT = "yyyy-MM-dd";
    private static final String TIME_FORMAT = "HH:mm:ss";

    @Override
    public Date convert(String value) {
        if (StringUtils.isEmpty(value)) {
            return null;
        }
        value = value.trim();
        try {
            if (value.contains(TIME_SPLIT)) {
                try {
                    return DateUtils.parseDate(value, DATE_TIME_FORMAT);
                } catch (Exception exception) {
                    return DateUtils.parseDate(value, TIME_FORMAT);
                }
            } else {
                return DateUtils.parseDate(value, DATE_FORMAT);
            }
        } catch (Exception exception) {
            log.error("string value[{}] can not format to date, please check it", value);
            return null;
        }
    }
}
